import { download, getBase64, zTypeof } from '@/utils'
import { Message } from 'element-ui'
const axios = require('axios')
const instance = axios.create({
  baseURL: 'http://39.104.162.130:3000',
  // baseURL: 'http://localhost:3000',
  timeout: 6000
})

instance.interceptors.request.use(config => {
  console.log(config, 'config')
  return config
}, err => {
  return Promise.reject(err)
})

// 添加响应拦截器
instance.interceptors.response.use(async response => {
  if (!response) {
    return
  }
  console.log(response, 'res')
  const res = response.data
  const headers = response.headers
  if (zTypeof(res) === 'blob') {
    if (
      headers['content-type'] &&
      headers['content-type'].includes('application/json')
    ) {
      const reader = new FileReader()
      reader.onload = e => {
        const res = JSON.parse(reader.result)
        if (!res.message) res.message = '下载错误'
        Message.error(res.message)
      }
      reader.readAsText(response.data, 'utf-8')
      return Promise.reject(new Error(res.message))
    } else {
      const fileBase64 = await getBase64(res)
      if (response.config.headers && response.config.headers.isDown === '1') {
        const content = response.headers['content-disposition']
        const fileName = content && content.split(';')[1].split('filename=')[1]
        download({
          fileName: decodeURIComponent(fileName),
          content: res
        })
        return Promise.resolve()
      } else {
        return Promise.resolve(fileBase64, response)
      }
    }
  }
  return response
}, err => {
  if (err.response) {
    console.log('响应拦截器:err-data', err.response)
  }
  return Promise.resolve(err)
})

// function timeout (ms) {
//   return new Promise((resolve, reject) => {
//     setTimeout(resolve, ms)
//   })
// }
// let intervalId = null
export const request = async (API, method = 'GET', query = {}, data = {}, isDown = false) => {
  const options = {
    url: API,
    method: method,
    params: query,
    data: data
  }
  if (isDown) {
    options.responseType = 'blob'
    options.headers = {
      isDown: '1'
    }
  }
  const res = await instance.request(options)
  return res.data
}
